package indi.lqzhi.basic.ui.basic.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.annotation.LayoutRes;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import java.util.ArrayList;
import java.util.List;

public class ListViewAdapter<V, Bind extends ViewDataBinding> extends BaseAdapter {

    private Context context;

    private List<V> datas;

    private Bind bind;

    @LayoutRes
    private int layoutId;

    private OnHandler<V,Bind> onHandler;


    public ListViewAdapter(Context context, int layoutId) {
        this.datas = new ArrayList<>(1);
        this.context = context;
        this.layoutId = layoutId;
    }

    public ListViewAdapter(Context context, List<V> datas, int layoutId) {
        this.datas = datas;
        this.context = context;
        this.layoutId = layoutId;
    }

    public ListViewAdapter(Context context, int layoutId, OnHandler<V, Bind> onHandler) {
        this.datas = new ArrayList<>(1);
        this.context = context;
        this.layoutId = layoutId;
        this.onHandler = onHandler;
    }

    public ListViewAdapter(Context context, List<V> datas, int layoutId, OnHandler<V, Bind> onHandler) {
        this.datas = datas;
        this.context = context;
        this.layoutId = layoutId;
        this.onHandler = onHandler;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int i) {
        return datas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        //获取到数据
        if (datas.isEmpty()) {
            //数据为空
            return view;
        }
        V v = datas.get(i);//取出数据
        @SuppressLint("ViewHolder") View rootView =
                LayoutInflater.from(context).inflate(layoutId, viewGroup);//获取到View
        if (onHandler != null){
            bind = DataBindingUtil.bind(rootView);
            onHandler.dispose(this,i,v,bind);//设置数据
        }
        return rootView;
    }

    public interface OnHandler<V, Bind extends ViewDataBinding> {
        void dispose(ListViewAdapter<V, Bind> adapter, int postion, V value, Bind bind);
    }
}
